package com.seezoon.application.user.executor;

import com.seezoon.application.user.dto.UserPwdLoginCmd;
import com.seezoon.application.user.dto.clientobject.LoginCO;
import com.seezoon.domain.service.user.CaptchaService;
import com.seezoon.domain.service.user.LoginService;
import com.seezoon.domain.service.user.UserPasswdVerifyService;
import com.seezoon.domain.service.user.vo.CaptchaVO;
import com.seezoon.domain.service.user.vo.LoginTokenVO;
import com.seezoon.infrastructure.dto.Response;
import com.seezoon.infrastructure.error.ErrorCode;
import com.seezoon.infrastructure.properties.AppProperties;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

/**
 * 账号密码登录
 */
@RequiredArgsConstructor
@Slf4j
@Component
@Validated
public class UserPwdLoginCmdExe {

    private final CaptchaService captchaService;
    private final UserPasswdVerifyService userPasswdVerifyService;
    private final LoginService loginService;
    private final AppProperties appProperties;

    public Response<LoginCO> execute(@Valid @NotNull UserPwdLoginCmd cmd) {
        boolean verify = captchaService.verify(cmd.getUsername(), CaptchaVO.TYPE_USER_LOGIN, cmd.getCaptchaText(),
                cmd.getCaptchaToken());
        if (!verify && appProperties.getCodeValidateEnabled()) {
            return Response.error(ErrorCode.CAPTCHA_NOT_MATCH);
        }

        boolean verified = userPasswdVerifyService.verify(cmd.getUsername(), cmd.getPassword());
        if (!verified) {
            return Response.error(ErrorCode.USER_PWD_ERROR);
        }
        LoginTokenVO loginTokenVO = loginService.loginByUserName(cmd.getUsername());
        LoginCO co = new LoginCO();
        co.setAccessToken(loginTokenVO.getAccessToken());
        co.setAccessTokenExpire(loginTokenVO.getAccessTokenExpire());
        co.setRefreshToken(loginTokenVO.getRefreshToken());
        co.setRefreshTokenExpire(loginTokenVO.getRefreshTokenExpire());
        return Response.success(co);
    }
}
